package com.difsonapps.android.marker.activities;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.User;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmLoginFacebookActivity extends Activity {
	public static final String EXTRA_USERID = "com.difsonapps.android.marker.extra.USERID";
	public static final String EXTRA_USERNAME = "com.difsonapps.android.marker.extra.USERNAME";
	public static final String EXTRA_USERPIC = "com.difsonapps.android.marker.extra.USERPIC";


	ProgressDialog loadingProgressDialog;
	
	String id;//User facebook id
	String name;
	String pict;
	
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
	
	NetworkImageView profileImageView;
	TextView errorTextView;
	TextView usernameTextView;
	TextView page_title;
	EditText passwordEditText;
	EditText confirmPasswordEditText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_confirm_login_facebook);
		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));
		

        errorTextView = (TextView) findViewById(R.id.errorTextView);
		
		profileImageView = (NetworkImageView)findViewById(R.id.profileImageView);
		usernameTextView = (TextView)findViewById(R.id.usernameTextView);
		page_title = (TextView)findViewById(R.id.page_title);
		passwordEditText = (EditText)findViewById(R.id.passwordEditText);
		confirmPasswordEditText = (EditText)findViewById(R.id.confirmPasswordEditText);
		
		id = getIntent().getStringExtra(EXTRA_USERID);
		name = getIntent().getStringExtra(EXTRA_USERNAME);
		pict = getIntent().getStringExtra(EXTRA_USERPIC);
		
		if(name!=null) {
			usernameTextView.setText(name);
			page_title.setText(getResources().getString(R.string.welcome)+" "+name+"");
		}
		if(pict!=null){
			profileImageView.setImageUrl(pict, imageLoader);
		}
		//TODO Afficher la photo ici
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	public void btnConfirmClick(View v){
		confirm();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.confirm_login_facebook, menu);
		return true;
	}

	private void showProgress(){
		loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		//loadingLayout.setVisibility(View.VISIBLE);
	}
	
	private void hideProgress(){
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
		//loadingLayout.setVisibility(View.GONE);
	}
	private void confirm(){
		String password = passwordEditText.getText().toString().trim();
		String confirmPassword = confirmPasswordEditText.getText().toString();
		if(password.equals("")){
			toast(getResources().getString(R.string.type_password));
			return;
		}
		if(!password.equals(confirmPassword)){
			toast(getResources().getString(R.string.passwords_not_match));
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
        params.put("password", MarkerUtil.md5(password));
        params.put("id", id);
        
		showProgress();
		
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.confirmFbUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonConfirm(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonConfirm(JSONObject response){
		try {
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("authenticated")){
					User user = User.parseFromJsonObject(response);
	            	if(user==null){
	            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
	            		errorTextView.setVisibility(View.VISIBLE);
	            		return;
	            	}else{
						Intent result = new Intent();
						result.putExtra(RegisterActivity.EXTRA_USER, user);
						result.putExtra(RegisterActivity.EXTRA_AUTH, true);
						setResult(RESULT_OK, result);
						finish();
	            	}
	            	hideProgress();
					return;
				}
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
		errorTextView.setText(getResources().getString(R.string.an_error_occured));
		errorTextView.setVisibility(View.VISIBLE);
        hideProgress();
	}

	public void toast(String text){
		Toast.makeText(this, text,Toast.LENGTH_LONG).show();
	}

}
